<template>
	<view class="content">
		<view class="search-wrap">
			<u-search placeholder="请输入小区名称" disabled v-model="keyword"
				@click="$u.debounce(handleSearchClick,$debounceTime,true)" :show-action="false"></u-search>
		</view>
		<view class="map-wrap">
			<map id="map" @markertap="handleMarkerClick" @regionchange="handleRegionchange" :scale="scale" class="map" :latitude="location.latitude"
				show-location :longitude="location.longitude">
				<cover-image v-if="positionImgShow" class="position-img"
					:src="icon3"></cover-image>
				<cover-image @click="handleReturnPositionClick" v-if="positionImgShow" class="return-position"
					:src="icon4"></cover-image>
			</map>
		</view>
		<view class="bottom-outer">
			<uni-transition :mode-class="['fade','slide-bottom']" :show="bottomOperateShow">
				<view class="bottom-container">
					<view class="bottom-01">
						<view>{{otherDetails.title}}</view>
						<view class="bottom-01-right">
							<text>可用端口数：</text><text>{{otherDetails.available}}</text><text>/{{otherDetails.total}}</text>
						</view>
					</view>
					<view class="bottom-02">{{otherDetails.subTitle}}</view>
					<view class="bottom-03">
						<u-tag class="bottom-03-tag" v-for="(item,i) in labelList" :key="i"  :text="item.name" mode="dark"
							shape="circle" :bg-color="item.open==1?'#909399':'#4CBBAF;'" size="mini" />
					</view>
					<view class="bottom-04">
						<view v-for="(item,i) in otherDetails.worthList" :key="i">
							<text>{{item.power}}</text><text class="bottom-04-text">{{item.price}}</text>
						</view>
					</view>
					<view class="bottom-05">{{promptText}}</view>
					<view class="bottom-06">
						<view @click="handleErrorClick">
							<image mode="widthFix" :src="icon2">
							</image>
							<text>位置错误上报</text>
						</view>
						<view @click="handleNavigationClick">
							<image mode="widthFix" :src="icon">
							</image>
							<text>开始导航</text>
						</view>
					</view>
					<view class="bottom-safe-area"></view>
				</view>
			</uni-transition>
		</view>
	</view>
</template>
<script>
	var list=[];//存储接口数据，只为了在点击makers点时，拿详细数据，展示底部弹窗;
	import {
		getMapUrl,commonParams
	} from '@/env.js';
	export default {
		data() {
			return {
				icon2:this.$imgUrl+'map/map-close.png',
				icon:this.$imgUrl+'map/map-03.png',
				icon3:this.$imgUrl+'map/map-01.png',
				icon4:this.$imgUrl+'map/map-07.png',
				//search
				keyword: '',
				//map
				scale:14,
				positionImgShow: false, //中心点固定图片
				mapContext: null,
				location: {//默认北京
					longitude: 116.39747,
					latitude: 39.908823,
				},
				isPosition: true,//未地理位置授权时只允许只访问一次
				//current position 存储用户当前位置经纬度，与地图经纬度分开，因为用户会移动的
				currentLocation: {
					longitude: '',
					latitude: '',
				},
				//bottom
				id:'',//接口中需要的id
				navigationData:{//导航要去的微信内置地图
					name:'',
					longitude: '',
					latitude: '',
					address:''
				},
				bottomOperateShow: false,
				labelList: [],
				otherDetails:{
					title:'',
					subTitle:'',
					total:'',
					available:'',
					worthList:[]
				},
				promptText:'',//底部弹出层中提示文字;
			}
		},
		watch: {
			
			location(newVal, oldVal) {
				this._hideLayer();
				this.getMapDataRequest(newVal);
			}
		},
		onLoad() {
			
			this.mapContext = uni.createMapContext("map");
			this._useAggregation();
		},
		onShow() {
			this._isAuthorize();
			let that=this;			
		},
		methods: {
			//search
			handleSearchClick() {
				uni.navigateTo({
					url: '/pages/map/search'
				});
			},
			//map
			handleReturnPositionClick() {
				
				this.mapContext.moveToLocation({
					success: (e) => {
						this._hideLayer();
						
						uni.getLocation({
							type: 'gcj02',
							success: res => {
								
								let location = {
									longitude: res.longitude,
									latitude: res.latitude,
								};
								this.getMapDataRequest(location);
							},
							fail: (err) => {
								
								//失败时，获取存储的用户当前定位点信息
								this.getMapDataRequest(this.currentLocation);
							}
						});
					}
				})
			},
			handleRegionchange(e) {
				
				if(this.positionImgShow){
					//拖拽结束
					if (e.type == 'end' && e.causedBy == 'drag') {
						this._hideLayer();
						
						this.keyword='';
						
						this.getMapDataRequest(e.detail.centerLocation);
						
					};
					//缩放结束
					if (e.type == 'end' && e.causedBy == 'scale') {
						this._hideLayer();
					};
				};
			},
			
			getMapDataRequest(centerLocation) {
				
				

				this.mapContext.addMarkers({
					markers: [],
					clear: true,
				});
				uni.request({
					url: getMapUrl,
					method: 'POST',
					data: {
						userid_locked: uni.getStorageSync('userId'),
						...centerLocation,
						...commonParams,
						meter:2000,
					},
					success: res => {
						let len = res.data.data.list.length;
						
						if (len) {
							let resList = res.data.data.list;
							list=resList;
							this.promptText=res.data.data.tips;
							let markers = [];
							for (let i = 0; i < len; i++) {
								let obj = {
									id: i + 1, //注意makers点id如果不唯一会导致清除不了markers点
									iconPath: this.$imgUrl+'map/map-08.png',
									width: 26,
									height: 31,
									joinCluster: true, 
									latitude: parseFloat(resList[i].latitude),
									longitude: parseFloat(resList[i].longitude),
								};
								markers.push(obj);
							};
							
							this.mapContext.addMarkers({
								markers,
								clear:true,
								success:()=>{
									
								},
								complete:res=>{
									
								}
							});
							
						};
					},
					fail: err => {}
				});
			},
			
			_useAggregation() {
				
				this.mapContext.initMarkerCluster({
					enableDefaultStyle: false,
					zoomOnClick: true,
					gridSize: 60,
					complete(res) {

					}
				});
				this.mapContext.on('markerClusterCreate', res => {
					const clusters = res.clusters;
					const markers = clusters.map(cluster => {
						const {
							center,
							clusterId,
							markerIds
						} = cluster;
						return {
							...center,
							width: 39,
							height: 46,
							clusterId, // 必须
							iconPath: this.$imgUrl+'map/map-08.png',
							
						}
					});
					this.mapContext.addMarkers({
						markers,
						complete(res) {
							
						}
					})
				})
			},
			
			handleMarkerClick(e){
				
				let index=e.markerId-1;	
				let id=list[index].community_id;
				this.id=id;
				this.getMapDetailRequest();
				//将地图中心点移动到
				let obj={
					latitude:parseFloat(list[index].latitude),
					longitude:parseFloat(list[index].longitude),
				}
				this.mapContext.moveToLocation(obj);
			},
			//查询marker点接口数据
			getMapDetailRequest(){
				this.$u.api.getMapDetail({
					
					community_id:this.id,
				}).then(res=>{
					if(res.result_code==318){
						this.labelList=res.data.button;
						this.otherDetails={
							title:res.data.community_name,
							subTitle:res.data.address,
							total:res.data.power_count,
							available:res.data.power_count_use_no,
							worthList:res.data.fee,
						};
						//显示底部弹窗
						this.bottomOperateShow=true;
						
						this.navigationData={
							latitude:parseFloat(res.data.latitude),
							longitude:parseFloat(res.data.longitude),
							name:res.data.community_name,
							address:res.data.address,
						};
						
					}
				}).catch();
			},
			
			_hideLayer(){
				this.bottomOperateShow=false;
				this.id=''; 
				this.navigationData={};
				this.otherDetails={};
				this.promptText='';
			},
			handleErrorClick(){
				this.$u.api.getMapError({
					
					community_id:this.id,
				}).then(res=>{
					this.$utils.modal({
						title: '温馨提示',
						content: res.msg,
						showCancel: false,
					});
				}).catch();
			},
			handleNavigationClick(){
				uni.openLocation({
					...this.navigationData,
					success: function () {
						console.log('success');
					}
				});
			},
			//current position
			_isAuthorize() {
				
				
				
				// #ifdef	MP-ALIPAY
				uni.getLocation({
					type: 'gcj02',
					success:res=>{
						if (this.isPosition) {
							
							//驱动地图移动到用户当前定位点
							this.location = {
								longitude: res.longitude,
								latitude: res.latitude,
							};
							//存储当前用户定位点
							this.currentLocation = {
								longitude: res.longitude,
								latitude: res.latitude,
							};
							this.positionImgShow = true;
							this.isPosition = false;
						}
					}
				});
				// #endif
				
				//微信
				// #ifdef	MP-WEIXIN
				const that = this;
				uni.authorize({
					scope: 'scope.userLocation',
					success() {
						that._getLocation();
					},
					fail() {
						that._openAuthorizeModal();
					}
				});
				// #endif
			},
			_getLocation() {
				uni.getLocation({
					type: 'gcj02',
					success: res => {
						
						if (this.isPosition) {
							
							//驱动地图移动到用户当前定位点
							this.location = {
								longitude: res.longitude,
								latitude: res.latitude,
							};
							//存储当前用户定位点
							this.currentLocation = {
								longitude: res.longitude,
								latitude: res.latitude,
							};
							this.positionImgShow = true;
							this.isPosition = false;
						}
					},
					fail: () => {
						// this.$utils.modal({
						// 	title: '温馨提示',
						// 	content: '为了您能享受更好的服务，请先开启手机定位！',
						// 	showCancel: false,
						// 	callback: () => {}
						// });
					}
				});
			},
			_openAuthorizeModal() {
				this.$utils.modal({
					title: '请求授权当前位置',
					content: '需要获取您的地理位置，请确认授权',
					callback: (bool) => {
						if (bool) {
							uni.openSetting();
						} else {
							this.$utils.toast('您拒绝了授权，无法获得您的位置');
						}
					}
				});
			}
		},
	}
</script>
<style lang="scss" scoped>
	.content {
		height: 100%;
		box-sizing: border-box;
		padding-top: 52px;
		overflow: hidden;
	}

	.search-wrap {
		padding: 10px;
		background-color: #fff;
		height: 52px;
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		box-sizing: border-box;
	}

	.map-wrap {
		height: 100%;
	}

	.map {
		width: 100%;
		height: 100%;
		position: relative;
		z-index: 10;
	}

	.position-img {
		width: 100rpx;
		height: 100rpx;
		position: absolute;
		left: 50%;
		bottom: 50%;
		transform: translateX(-50%);
		z-index: 11;
	}

	.return-position {
		padding:10rpx;
		background-color:#fff;
		border-radius:50%;
		width: 70rpx;
		height: 70rpx;
		position: absolute;
		right: 20px;
		top: 20px;
		z-index: 11;
	}

	.bottom-01 {
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #dedede;
		padding-bottom: 20rpx;
	}

	.bottom-01>view:first-child {
		font-size: 38rpx;
		font-weight: bold;
	}

	.bottom-01-right text:nth-child(1) {
		font-size: 28rpx;
		color: #666;
	}

	.bottom-01-right text:nth-child(2) {
		font-size: 34rpx;
		color: #4CBBAF;
	}

	.bottom-01-right text:nth-child(3) {
		font-size: 34rpx;
		font-weight: bold;
	}

	.bottom-outer {
		position: absolute;
		left: 0;
		bottom: 0;
		width: 100%;
		z-index: 100;

	}

	.bottom-container {
		background-color: #fff;
		padding: 20rpx;
	}

	.bottom-02 {
		font-size: 28rpx;
		color: #666;
		padding: 14rpx 0;
	}

	.bottom-03-tag {
		margin-right: 20rpx;
	}

	.bottom-04 {
		font-size: 28rpx;
		color: #666;
		padding-top: 14rpx;
	}
	.bottom-04 text{
		color:#4CBBAF;
	}
	.bottom-04 .bottom-04-text{
		padding-left:20rpx;
		color:#333;
	}
	.bottom-05 {
		font-size: 24rpx;
		color: #FA3534;
		padding: 10rpx 0;
		border-bottom: 1px solid #dedede;
	}

	.bottom-06 {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
	}

	.bottom-06 image {
		width: 50rpx;
		height: 50rpx;
		vertical-align: middle;
		margin-right: 10rpx;
	}

	.bottom-06 text {
		vertical-align: middle;
		line-height: 1;
		font-size: 28rpx;
	}

	.bottom-06>view:first-child {
		border: 1px solid #FA3534;
		border-radius: 10rpx;
		padding: 10rpx 20rpx;
		color: #FA3534;
	}

	.bottom-06>view:last-child {
		border-radius: 10rpx;
		padding: 10rpx 20rpx;
		background-color: #4CBBAF;
		color: #fff;
	}
</style>
<style>
	page {
		height: 100%;
		overflow: hidden;
	}
</style>
